package com.example.shopping_boot.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.shopping_boot.config.enums.RoleEnum;
import com.example.shopping_boot.mapper.SysUserMapper;
import com.example.shopping_boot.mapper.SysUserRoleMapper;
import com.example.shopping_boot.mapstruct.SysUserConverter;
import com.example.shopping_boot.pojo.dto.SysUserDTO;
import com.example.shopping_boot.pojo.entity.SysUserDO;
import com.example.shopping_boot.pojo.entity.SysUserRoleDO;
import com.example.shopping_boot.service.ISysUserService;
import com.example.shopping_boot.util.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Objects;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 翟羽佳
 * @since 2022-10-21
 */
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserDO> implements ISysUserService {

    private final SysUserMapper sysUserMapper;

    private final SysUserRoleMapper sysUserRoleMapper;

    private final RedisUtil redisUtil;

    @Override
    public String login(SysUserDTO sysUser) {
        // 1. 根据用户输入的用户名进行查询
        SysUserDO userDB = sysUserMapper.selectOne(Wrappers.<SysUserDO>lambdaQuery()
                .eq(SysUserDO::getName, sysUser.getName())
                .or()
                .eq(SysUserDO::getPhone, sysUser.getName()));

        if (!ObjectUtils.isEmpty(userDB)) {
            // 比较密码
            if (SysUserConverter.INSTANCE.toDto(userDB).getPassword().equals(sysUser.getPassword())) {

                redisUtil.delete("PermissionList", userDB.getId());
                redisUtil.delete("RoleList", userDB.getId());

//                登录
                StpUtil.login(userDB.getId(), "PC");

                return StpUtil.getTokenValue();
            } else {
                throw new RuntimeException("密码输入有误!");
            }
        } else {
            throw new RuntimeException("用户名或手机号不存在!");
        }
    }

    @Override
    public Boolean register(SysUserDTO sysUser) {
        SysUserDO userDB = sysUserMapper.selectOne(Wrappers.<SysUserDO>lambdaQuery().eq(SysUserDO::getName, sysUser.getName()).or().eq(SysUserDO::getPhone, sysUser.getPhone()));

        if (Objects.isNull(userDB)) {
            this.addUserRole(SysUserConverter.INSTANCE.toDo(sysUser),RoleEnum.USER);
            return true;
        } else {
            throw new RuntimeException("用户名或手机号已存在!!!");
        }
    }

    @Override
    public Boolean addUserRole(SysUserDO sysUserDO,RoleEnum roleEnum) {
        this.baseMapper.insert(sysUserDO);
        if (sysUserRoleMapper.insert(SysUserRoleDO.builder().userId(sysUserDO.getId()).roleId(roleEnum.getId()).build())>0) {
            return true;
        }
        return false;
    }


}
